package Server;

import model.*;
import util.Io;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 编程实现客户端的主功能实现
 */
public class ServerView {
    private ServerInitClose sic;
    private ServerDao dao;

    // 使用构造方法实现对对象的初始化操作
    public ServerView(ServerInitClose sic, ServerDao dao) {
        this.sic = sic;
        this.dao = dao;
    }

    private ArrayList<Student> students = null; //学员集合
    private ArrayList<StudentScore> studentScores = new ArrayList<>(); //学员分数集合
    private ArrayList<Topic> topics = new ArrayList<>(); //考题集合

    /**
     * 自定义成员方法实现对客户端发送过来的消息接收，并回发消息
     */
    public void serverReceive() throws IOException, ClassNotFoundException {
        // 进服务端先读取每个学生的信息
        students = Io.read();
        out:
        while (true) {
            // 读学生信息到系统

            students = Io.read();
            //读取文件考题到系统
            topics = Io.readTopic();
            System.out.println("等待数据的到来...");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 使用输入流进行接收
            sic.getOos().reset();
            Object object = sic.getOis().readObject();
            System.out.println("接收到的消息是:" + object);




            if (object instanceof UserMassage) {
                UserMassage message = (UserMassage) object;
                //todo 管理员检查的方法
                if (message.getType().equalsIgnoreCase("managerCheck")) {

                    serverManagerCheck(message);
                    continue out;
                }
                //todo 退出系统的方法
                if ("clientExit".equalsIgnoreCase(message.getType())) {
                    serverExit();
                    return;
                }



            }


            if (object instanceof StudentMessage) {
                StudentMessage message = (StudentMessage) object;
                //System.out.println("执行的操作" + message.getType()+",接收到的用户为:"+message.getUser());

                // todo 学生检查的方法

                if ("userCheck".equalsIgnoreCase(message.getType())) {
                    System.out.println("你好欢迎使用");
                    // 读取每个学生的信息
                    students.add(new Student(new User("oyz","123")));
                    for (Student s : students) {
                        // 调用方法实现对学生的检验
                        UserDao dao = new UserDao(s);
                        if (dao.judgeStudent(message.getUser().getUserName())) {
                            //Io.readScore(s);
                            System.out.println("读取分数信息成功!");
                            StudentMessage tum = new StudentMessage("success", s);
                            System.out.println("服务器发送学生校验成功!");
                            //回发数据
                            sic.getOos().reset();
                            sic.getOos().writeObject(tum);
                            System.out.println("服务器发送用户校验信息成功");
                            continue out;
                        }
                    }

                    message.setType("fail");//将状态改为失败
                    //回发数据
                    sic.getOos().writeObject(message);
                    System.out.println("服务器发送用户校验信息成功");
                    continue;
                }
                // todo 验证学生修改密码的方法
                if("updatePassword".equalsIgnoreCase(message.getType())){
                    System.out.println("修改密码成功");
                    message.setType("success");
                    sic.getOos().reset();
                    sic.getOos().writeObject(message);

                }





                /**
                 * 添加学生
                 */

                if ("addStudent".equalsIgnoreCase(message.getType())) {
                    if (!students.isEmpty()) {
                        for (Student s : students) {
                            System.out.println("开始遍历学生...");
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            if (message.getStudent().getId() == s.getId()) {
                                message.setType("学生已经存在");
                                sic.getOos().reset();
                                sic.getOos().writeObject(message);
                                System.out.println("添加失败");
                                continue out;
                            }
                            // 将学生添加入集合
                            students.add(message.getStudent());
                            // 将学生写入文件
                            Io.write(students);
                            message.setType("添加学生成功");
                            sic.getOos().reset();
                            sic.getOos().writeObject(message);
                            System.out.println("服务器添加学生成功");
                            continue;
                        }
                    }
                }
                /**
                 * 删除学生
                 */
                if ("deleteStudent".equalsIgnoreCase(message.getType())) {
                    if (students.isEmpty()) {
                        message.setType("系统里没有学生的信息");
                        sic.getOos().reset();
                        sic.getOos().writeObject(message);
                        continue;
                    } else {
                        Iterator<Student> iterator = students.iterator();
                        while (iterator.hasNext()) {
                            if (iterator.next().getId() == message.getStudent().getId()) {
                                iterator.remove(); //移除该学生对象
                                message.setType("删除该学生成功");
                                sic.getOos().reset();
                                sic.getOos().writeObject(message);
                                System.out.println("服务器删除学生对象成功");
                                continue out;
                            }

                        }

                    }
                }
                /**
                 * 修改学生
                 */
                if ("updateStudent".equalsIgnoreCase(message.getType())) {
                    if (students.isEmpty()) {
                        message.setType("系统里没有学生的信息");
                        sic.getOos().reset();
                        sic.getOos().writeObject(message);
                        System.out.println("系统里没有学生信息");
                        continue;
                    } else {
                        int index = 0;
                        for (Student s : students) {
                            if (s.getId() == message.getStudent().getId()) {
                                // 如果存在该id，就换掉原来的集合里对应位置student对象
                                students.set(index, message.getStudent());
                                Io.write(students);
                                message.setType("修改学生成功");
                                sic.getOos().reset();
                                sic.getOos().writeObject(message);
                                System.out.println("服务器修改学生成功");
                                continue out;
                            }
                            index++;
                        }
                        message.setType("想要修改的id不存在");
                        sic.getOos().reset();
                        sic.getOos().writeObject(message);
                        System.out.println("想要修改的id不存在");
                        continue;
                    }
                }
                /**
                 * 查找学生
                 */
                if ("searchStudent".equalsIgnoreCase(message.getType())) {
                    if (students.isEmpty()) {
                        message.setType("系统里没有学生的信息");
                        sic.getOos().reset();
                        sic.getOos().writeObject(message);
                        System.out.println("系统里没有学生信息");
                        continue;
                    } else {
                        for (Student s : students) {
                            if (s.getId() == message.getStudent().getId()) {
                                // 将查到的学生对象传递给message类,向客户端发送
                                message.setStudent(s);
                                sic.getOos().reset();
                                sic.getOos().writeObject(message);
                                System.out.println("服务器查找成功");
                                continue out;
                            }
                            message.setType("学员id不存在");
                            sic.getOos().reset();
                            sic.getOos().writeObject(message);
                            System.out.println("学员id不存在");
                            continue;
                        }
                    }
                }


                /**
                 * 学员修改密码
                 */
                if ("updatePassword".equalsIgnoreCase(message.getType())) {
                    int index = 0;
                    for (Student s : students) {
                        if (s.getId() == message.getStudent().getId()) {
                            students.set(index, message.getStudent());
                            System.out.println("修改后的学生集合为:" + students);
                            Io.write(students);
                            message.setType("密码修改成功");
                            sic.getOos().reset();
                            sic.getOos().writeObject(message);
                            continue out;
                        }
                        index++;
                    }
                }
                /**
                 * 导出分数
                 */
                //todo 目的是为了从库里把所有成绩拿出来
                if ("saveScore".equalsIgnoreCase(message.getType())) {
                    System.out.println("-----------------------------------");
                    ArrayList<StudentScore> studentScores = Io.readScore();
                    //打印所有成绩
                    for (StudentScore s:studentScores){
                        System.out.println(s);
                    }
                    System.out.println("-----------------------------------");
                    /*
                    // 建立临时集合用来存在遍历出来的数据
                    ArrayList<StudentScore> tmp = new ArrayList<>();
                    // 遍历集合里边的分数
                    for (StudentScore s : this.studentScores) {
                        // 如果该分数属于这个学生，就放入集合
                        if (s.getStudent().getId() == message.getStudent().getId()) {
                            tmp.add(s);
                        }
                    }
                    // 将分数导出进入系统
                    Io.saveSore(tmp);*/
                    message.setType("导出成绩");
                    sic.getOos().reset();
                    sic.getOos().writeObject(message);
                    System.out.println("服务器导出成功");

                }

                /**
                 * 查询分数
                 */
                if ("findScore".equalsIgnoreCase(message.getType())) {
                    ArrayList<StudentScore> studentScores = Io.readScore();
                    System.out.println("-------------------------------------");
                    for (StudentScore s:studentScores){
                        if(s.getStudent().getName().equals(message.getStudent().getName())){
                            System.out.println((message.getStudent().getName())+" 的成绩为: "+s.getScore());
                        }
                    }
                    System.out.println("--------------------------------------");
                    message.setType("查询成绩");
                    sic.getOos().reset();
                    sic.getOos().writeObject(message);
                    System.out.println("服务器将分数发送给客户端成功");
                }
                /**
                 * 如果读到的对象是考题消息执行的操作
                 */
                if (object instanceof TopicMessage) {
                    TopicMessage topicMessage = (TopicMessage) object;
                    System.out.println("准备发送考题");
                    /**
                     * 增加考题
                     */
                    if ("addTopic".equalsIgnoreCase(topicMessage.getType())) {
                        if (!topics.isEmpty()) {
                            for (Topic t : topics
                            ) {
                                if (topicMessage.getTopic().getId() == t.getId()) {
                                    topicMessage.setType("此考题已存在");
                                    sic.getOos().reset();
                                    sic.getOos().writeObject(topicMessage);
                                    System.out.println("此考题已存在");
                                    continue out;
                                }
                            }
                            //将学生写入集合
                            topics.add(topicMessage.getTopic());
                            //将学生集合写入文件
                            Io.saveTopic(topics);
                            topicMessage.setType("添加考题成功");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("服务器添加考题成功");
                            continue;
                        } else {
                            topics.add(topicMessage.getTopic());
                            //将学生集合写入文件
                            Io.saveTopic(topics);
                            topicMessage.setType("添加考题成功");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("服务器添加考题成功");
                            continue;
                        }
                    }
                    /**
                     * 删除考题
                     */
                    if ("deleteTopic".equalsIgnoreCase(topicMessage.getType())) {
                        if (students.isEmpty()) {
                            //如果为空则修改studentMessage
                            topicMessage.setType("系统内没有此考题");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("系统内没有此考题");
                            continue;
                        } else {

                            Iterator<Topic> iterator = topics.iterator();
                            while (iterator.hasNext()) {
                                if (iterator.next().getId() == topicMessage.getTopic().getId()) {
                                    iterator.remove();//如果id存在 则移除集合中的topic
                                    Io.saveTopic(topics);//将删除后的集合重新写入 覆盖源文件
                                    topicMessage.setType("删除考题成功");
                                    sic.getOos().reset();
                                    sic.getOos().writeObject(topicMessage);
                                    System.out.println("服务器删除考题成功");
                                    continue out;
                                }
                            }
                            topicMessage.setType("考题不存在");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("考题不存在");
                            continue;
                        }
                    }
                    /**
                     * 修改考题
                     */
                    if ("updateTopic".equalsIgnoreCase(topicMessage.getType())) {
                        if (topics.isEmpty()) {
                            topicMessage.setType("系统内没有学生信息");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("系统内没有学生信息");
                            continue;
                        } else {
                            int index = 0;
                            for (Topic t : topics) {
                                if (t.getId() == topicMessage.getTopic().getId()) {
                                    topics.set(0, topicMessage.getTopic());//如果id存在 则将传来的student赋值给原来的student
                                    Io.saveTopic(topics);//重新写入文件覆盖原文件
                                    System.out.println("服务器修改考题成功");
                                    topicMessage.setType("修改考题成功");
                                    sic.getOos().reset();
                                    sic.getOos().writeObject(topicMessage);
                                    continue out;
                                }
                                index++;
                            }
                            topicMessage.setType("想要修改的考题不存在");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("想要修改的考题不存在");
                            continue;
                        }
                    }
                    /**
                     * 查找考题
                     */
                    if ("searchTopic".equalsIgnoreCase(topicMessage.getType())) {
                        if (topics.isEmpty()) {
                            topicMessage.setType("系统内没有此考题信息");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("系统内没有此考题信息");
                            continue;
                        } else {
                            for (Topic t : topics) {
                                if (t.getId() == topicMessage.getTopic().getId()) {
                                    topicMessage.setType("查找考题成功");
                                    topicMessage.setTopic(t);//将查到学生信息覆盖原信息
                                    sic.getOos().reset();
                                    sic.getOos().writeObject(topicMessage);
                                    System.out.println("服务器查找考题成功");
                                    continue out;
                                }
                            }
                            topicMessage.setType("考题题号不存在");
                            sic.getOos().reset();
                            sic.getOos().writeObject(topicMessage);
                            System.out.println("考题题号不存在");
                            continue;
                        }
                    }
                }
            }

           /* // 将得到的消息发送给客户端
            sic.getOos().writeObject(object);
            System.out.println("消息发送成功!");*/
            /**
             * 如果传来的对象时考试有关
             */
            if (object instanceof StudentScoreMessage) {
                StudentScoreMessage studentScoreMessage = (StudentScoreMessage) object;
                /**
                 * 开始考试
                 */
                if (studentScoreMessage.getType().equalsIgnoreCase("startExam")) {
                    // 将题库发送给客户端
                    sic.getOos().reset();
                    sic.getOos().writeObject(topics);

                    continue out;
                }
                /**
                 * 结束考试 获取信息
                 */
                if (studentScoreMessage.getType().equalsIgnoreCase("endExam")) {
                    // 将客户端得到的分数对象传入分数集合
                    // studentScores.add(studentScoreMessage.getStudentScore());
                    // 从客户端读取那人考试的信息
                    studentScoreMessage = (StudentScoreMessage) sic.getOis().readObject();
                    System.out.println(studentScoreMessage);
                    System.out.println("考试结束");
                    continue out;
                }
            }
        }
    }



    // 增加人物的方法
    private void serverAddUser(UserMassage tum) {
    }

    // 退出系统的方法
    private void serverExit() {
        System.out.println("退出系统成功!");
    }

    // 管理员检查的方法
    private void serverManagerCheck(UserMassage tum) throws IOException {
        if(dao.serverManagerCheck(tum.getUser())){
            tum.setType("success");
            System.out.println("登录成功!");

        }else{
            tum.setType("fail");
            System.out.println("登录失败!");
        }
        // 回发数据
        sic.getOos().reset();
        sic.getOos().writeObject(tum);
        System.out.println("服务器发送管理员校验信息成功!");
    }
}
